package com.boxin.ims.modules.wechat.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.ad.entity.Advertisement;
import com.boxin.ims.modules.ad.service.AdvertisementService;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.sys.utils.RandomUtils;
import com.boxin.ims.modules.wechat.busi.BusinessProcessor;
import com.boxin.ims.modules.wechat.busi.ProcessMessage;
import com.boxin.ims.modules.wechat.entity.LotteryLog;
import com.boxin.ims.modules.wechat.entity.LotteryRecord;
import com.boxin.ims.modules.wechat.entity.NewsReply;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.thinkgem.jeesite.modules.sys.entity.User;

/**
 * @author Administrator
 * @date 2014-4-22
 * @function <p>获取并转移动广告奖品</p>
 */
@Service
public class AdvertisementLotteryProcessor extends BusinessProcessor{

	@Autowired
	AdvertisementService advertisementService;
	
	@Autowired
	LotteryRecordService lotteryRecordService;
	
	@Autowired
	LotteryLogService  lotteryLogService;
	
	@Override
	public ProcessMessage process() {
		WechatMember member = memberCheckAndReply();
		if(member  !=  null){
			//找到该用户下所有广告奖品(以手机号为准)
			List<LotteryRecord> lotteryList = advertisementService.findMyAdvertisementLotteryList(null, member);
			List<Advertisement>  adList = 	advertisementService.findMyAdvertisement(user.getId());
			
			List<LotteryRecord> myLotteryList = new ArrayList<LotteryRecord>();
			
			if(adList != null && !adList.isEmpty()){
				for(Advertisement ad : adList){
					////////
					if(lotteryList!=null  && !lotteryList.isEmpty()){
						for(LotteryRecord record : lotteryList){
							if(ad.getId() == record.getSourceId()){
								//生成新奖品
								LotteryRecord tempLottery = cloneLottery(record, user, member);
								lotteryRecordService.save(tempLottery);
								
								//生成日志
								generateAndSaveLotteryLog(tempLottery);
								
								//修改当前奖  的状态
								record.setStatus(LotteryRecord.STATUS_MOVE);
								record.setRemarks(record.getRemarks()+",奖品已转移至到广告主【"+user.getName()+"】平台上,新ID:"+tempLottery.getId());
								lotteryRecordService.save(record);
								
								//放回复列表中
								myLotteryList.add(tempLottery);
								
							}
						}
					}
				}
			}
			
			//回复
			if(myLotteryList != null && !myLotteryList.isEmpty()){
				
				
				if(myLotteryList.size()==1){	//单条奖品
					LotteryRecord map  =  lotteryList.get(0);
					Date date = (Date) map.getEndTime();
					String validDate = DateUtils.formatDate(
							(date == null) ? new Date() : date, "MM月dd日");
					
					String title = "您有未使用的奖品【" + map.getName() + "】";
					String desc = "亲，您有一份未使用的奖品【" + map.getName() + "】,请于"
							+ validDate + "之前到店里凭此二维码核销使用，过期作废，如果您想放弃本奖品请输入【放弃"+map.getId()+"】，谢谢！";
					writeSingleLotteryImageToUser(title, desc,map.getQrCode().getId());
					return null;
					
				}else{//多条奖品
					List<NewsReply> newsList = new ArrayList<NewsReply>();
					for (LotteryRecord row : myLotteryList) {
						NewsReply newsReply = new NewsReply();
						
						Date date = (Date) row.getEndTime();
						String validDate = DateUtils.formatDate(
								(date == null) ? new Date() : date, "MM月dd日");
						
						newsReply.setTitle("您有未使用的奖品【"+row.getName()+"】");
						newsReply.setDescription("您有未使用的奖品【"
								+ row.getName()+"】请于"+validDate+"之前到店里凭此打开的二维码到服务台核销使用,如果您想放弃本奖品请输入【放弃"+row.getId()+"】，谢谢!");
						newsReply.setPicUrl(QRCodeUtils.getQRCodePNGURL(row.getQrCode().getId()));
						newsReply.setUrl(QRCodeUtils.getQRCodePNGURL(row.getQrCode().getId()));
						newsList.add(newsReply);
					}

					writeQueryLotteryImageToUser(newsList); // 回复
					return null;
					
				}
				
			}else{
				
				
				//如果没有找到洗车卡
				String keywords = this.textMessage.getContent();
				
				if("洗车卡".equals(keywords)){
					//判断是否已经获得过
					
					LotteryRecord query = new LotteryRecord();
					query.setName("免费洗车卡");
					query.setMember(member);
					query.setCreateTime(null);
					
					List<LotteryRecord>  rList = 	lotteryRecordService.find(query);
					if(rList!=null && rList.size()>0){	//已经使用过
						
						String reply = "亲，对不起，您已经享用过本服务了!";
						writeToUser(reply);
					}else{
						
						
						int random  =  RandomUtils.randArrayInt(100);
						
						LotteryRecord record = new LotteryRecord();
						record.setUser(user);
						
						
						if(random >80){	//按一定的 比率显示为邯郸微购物
							record.setFromSeller("邯郸微购物");
						}
						
						
						record.setMember(member);
						record.setName("免费洗车卡");
						record.setSourceType(LotteryRecord.SURCE_TYPE_MOVED);
						record.setStatus(LotteryRecord.STATUS_NORMAL);
						record.setSourceId(0l);
						record.setEndTime(DateUtils.getDelayDate(10));
						lotteryRecordService.save(record);
						
						
						//判断是否还有余下的该奖品
						String validDate = DateUtils.formatDate((record.getEndTime()==null)?new Date():record.getEndTime(), "MM月dd日");
						String reply = "恭喜您，本次获得了【免费洗车卡】奖品,请务删除此信息,于"+validDate+"之前到店里凭此二维码核销使用,过期作废，如果您想放弃本奖品请输入【放弃"+record.getId()+"】，谢谢！";
						
						writeImageToUser("您有未使用的【免费洗车卡】",reply , record.getQrCode().getId());
						
					} 
					
				}
				
			}
			
			
			
		} 
		
		return null;
	}
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-22  下午5:13:27
	 * @function <p> 克隆奖品 </p>
	 * @param lotteryRecord
	 * @param user
	 * @param member
	 * @return
	 */
	public LotteryRecord cloneLottery(LotteryRecord lotteryRecord,User user,WechatMember member){
		LotteryRecord record = new LotteryRecord();
		
		record.setEndTime(lotteryRecord.getEndTime());
		record.setLottery(lotteryRecord.getLottery());
		record.setUser(user);
		record.setMember(member);
		record.setSourceId(lotteryRecord.getSourceId());
		record.setFromSeller(lotteryRecord.getUser().getName());
		record.setName(lotteryRecord.getName());
		record.setStatus(LotteryRecord.STATUS_NORMAL);
		record.setRemarks(member.getRemarks()+",本奖品是从商家【"+lotteryRecord.getUser().getName()+"】的微会员"+member.getName()+"("+member.getMobile()+")转移动过来的.");
		record.setSourceType(LotteryRecord.SURCE_TYPE_MOVED);
		
		return record;
		
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-22  下午5:13:51
	 * @function <p> 生成奖品日志 </p>
	 * @param lotteryRecord
	 * @return
	 */
	public LotteryLog generateAndSaveLotteryLog(LotteryRecord lotteryRecord){
		LotteryLog log = new LotteryLog();
		log.setMember(lotteryRecord.getMember());
		log.setName(lotteryRecord.getName());
		log.setRemarks(lotteryRecord.getRemarks());
		log.setSourceId(lotteryRecord.getSourceId());
		log.setStatus(lotteryRecord.getStatus());
		log.setUser(lotteryRecord.getUser());
		log.setType(lotteryRecord.getSourceType());
		
		lotteryLogService.save(log);
		
		return log;
	}
	
	

	@Override
	public boolean isNeedBeMember() {
		return true;
	}
	
	

}
